package cn.org.tpeach.nosql.tools;


import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.UUID;

public class StringUtils {
    public static final String EMPTY = "";
    public static final String BLANK = " ";
    public static DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }
    public static boolean isNotEmpty(CharSequence cs) {
        return !StringUtils.isEmpty(cs);
    }

    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(cs.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotBlank(String str) {
        return !StringUtils.isBlank(str);
    }
    /**
     * 为空时使用默认
     *
     * @param obj
     * @param defaultStr 默认字符串
     * @return
     */
    public static String defaultToString(Object obj, String defaultStr) {
        return obj == null ? defaultStr : obj.toString();
    }
    /**
     * obj为null时返回 null 不返回"null"字符串</br>
     * 不为null时使用toString
     *
     * @param obj
     * @return String
     */
    public static String defaultNullToString(Object obj) {
        return defaultToString(obj, null);
    }

    /**
     * obj为null时返回 "" 不返回"null"字符串</br>
     * 不为null时使用toString
     *
     * @param obj
     * @return StringIOUtil
     */
    public static String defaultEmptyToString(Object obj) {
        return defaultToString(obj, EMPTY);
    }


    /**
     *
     * Description:
     * <p>
     * 对象转为字符串。去除左右空白。null返回""
     * </p>
     *
     * @param obj 对象
     * @return 字符串
     *
     */
    public static String getTrimString(Object obj) {
        return defaultEmptyToString(obj).trim();
    }

    /**
     * @param obj
     * @description 把空字符转为null返回，主要用于数据表的插入
     */
    public static String getEmptyStrToNull(Object obj) {
        if (obj == null || EMPTY.equals(defaultNullToString(obj))) {
            return null;
        }
        return obj.toString();
    }

    /**
     * 判断字符串是否相等
     *
     * @param cs1
     * @param cs2
     * @return {@code true} if the CharSequences are equal, case sensitive, or both
     *         {@code null}
     */
    public static boolean equals(CharSequence cs1, CharSequence cs2) {
        return cs1 == null ? cs2 == null : cs1.equals(cs2);
    }

    public static boolean equalsIgnoreCase(CharSequence cs1, CharSequence cs2) {
        if(cs1 == null){
            return cs2 == null;
        }
        return cs2 == null ? false : cs1.toString().equalsIgnoreCase(cs2.toString());
    }
    public static String randomUUID() {
        return UUID.randomUUID().toString();
    }

    public static String simpleRandomUUID() {
        return UUID.randomUUID().toString().replace("-","");
    }


    public static String showHexStringValue(String value) {
        if(value == null){
            return null;
        }
        char[] chars = value.toCharArray();
        char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        StringBuffer sb = new StringBuffer();
        for (char c : chars) {
            Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
            if((c >= 32 && c <= 126) || (c==8 || c==9 || c==10 || c==13) || (c >= 0x4E00 &&  c <= 0x9FA5)
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                    || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                    || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS){
                sb.append(c);
            }else{
//				int intNum = c;
//				String s = "\\x" + StringUtils.numToHex8(intNum);
//				sb.append(s);
                sb.append("\\x");
                sb.append(hex[(c & 0xF0) >> 4] );
                sb.append(hex[(c & 0xF)] );
            }
        }
        return sb.toString();

    }
    public static int length(CharSequence cs) {
        return cs == null ? 0 : cs.length();
    }

    public static int byteLength(CharSequence cs, Charset charset) {
        return cs == null ? 0 : cs.toString().getBytes(charset).length;
    }

    public static boolean contains(CharSequence str, CharSequence searchStr) {
        return null != str && null != searchStr ? str.toString().contains(searchStr) : false;
    }
    public static boolean contains(CharSequence seq, int searchChar) {
        return isEmpty(seq) ? false : indexOf(seq,searchChar,0)  >= 0;
    }

    public static int indexOf(CharSequence cs, int searchChar, int start) {
        if (cs instanceof String) {
            return ((String)cs).indexOf(searchChar, start);
        }
        if (start < 0) {
            start = 0;
        }
        int length = cs.length();
        for(int i = start; i < length; i++) {
            if (cs.charAt(i) == searchChar) {
                return i;
            }
        }
        return -1;
    }
    public static int compareToLength(String s1, String s2) {
        if (s1 != null && s2 != null) {
            int len1 = s1.length();
            int len2 = s2.length();
            if (len1 != len2) {
                return len1 - len2;
            }
            return s1.compareTo(s2);
        }
        return 0;
    }
    /**
     * byte——>hexString
     *
     * @param bytes
     * @param isBlankSpace 是否按空格分开
     * @return
     */
    public static String bytesToHexString(byte[] bytes, boolean isBlankSpace) {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        boolean flag = false;
        for (byte b : bytes) {
            int v = b & 0xFF;
            String hex = Integer.toHexString(v);
            if (flag && isBlankSpace) {
                stringBuffer.append(BLANK);
            } else {
                flag = true;
            }
            if (v < 0x10) {
                stringBuffer.append('0' + hex);
            } else {
                stringBuffer.append(hex);
            }

        }
        return stringBuffer.toString().toUpperCase();
    }


    public static String repeat(String origin,int repeatCount){
        if(origin == null){
            return null;
        }else if(EMPTY.equals(origin) || repeatCount == 1){
            return origin;
        }
        if(repeatCount<=0){
            return EMPTY;
        }

        StringBuilder buf = new StringBuilder();
        for(int i=0;i<repeatCount;i++){
            buf.append(origin);
        }
        return buf.toString();
    }
    public static String repeat(char ch, int repeat) {
        char[] buf = new char[repeat];
        for (int i = repeat - 1; i >= 0; i--) {
            buf[i] = ch;
        }
        return new String(buf);
    }

    public static String getLengthHummanText(long bytes){
        String humenText;
        if(bytes >  9999*1024*1024){
            humenText = MathUtils.divide(2,bytes+"", "1073741824")+"GB";
        }else if(bytes >  9999*1024){
            humenText = MathUtils.divide(2,bytes+"", "1048576")+"MB";
        }else if(bytes >  9999){
            humenText = MathUtils.divide(2,bytes+"", "1024")+"KB";
        }else {
            humenText = bytes+"Bytes";
        }
        return humenText;
    }
    public static String getLengthHumman(int length){
        if(length> 150*1024){
            return MathUtils.divide(2,length+"", "1024")+"KB";
        }
        return length+" bytes";
    }

    public static String getCsvTypeStr(String s){
        if(StringUtils.isBlank(s)){
            s= "";
        }else  {
            boolean c = false;
            if(s.contains("\"")){
                c = true;
                s = s.replace("\"","\"\"");
            }
            if(s.contains(",") || s.contains("，")){
                c = true;
            }
            if(s.contains("\n")){
                c = true;
            }
            if(c){
                s = "\""+s+"\"";
            }
        }
        return s;
    }
}
